#if (UNITY_STANDALONE || UNITY_ANDROID || UNITY_IOS || UNITY_WSA || UNITY_WEBGL) && UNITY_EDITOR
using UnityEditor;
using UnityEditorInternal;
using UnityEngine;
using static MVC.View.FieldCollectionEntity;

namespace MVC.View
{
    public class InheritTypeWindow : EditorWindow
    {
        private ReorderableList fieldList;
        private Vector2 scrollPosition;
        private FCData data;

        internal static void Init(FCData data)
        {
            var window = GetWindow<InheritTypeWindow>("继承类型列表", true);
            window.data = data;
            window.Init();
        }

        private void Init()
        {
            fieldList = new ReorderableList(data.inheritTypes, typeof(InheritData), true, false, true, true)
            {
                elementHeightCallback = OnElementHeightCallback,
                drawElementCallback = OnDrawElementCallback,
                onAddCallback = OnAddElementCallback,
                onRemoveCallback = OnRemoveElementCallback
            };
        }

        private void OnRemoveElementCallback(ReorderableList list)
        {
            list.list.RemoveAt(list.index);
            SaveData();
        }

        private void OnAddElementCallback(ReorderableList list)
        {
            var inheritData = new InheritData();
            data.inheritTypes.Add(inheritData);
            SaveData();
        }

        private void OnGUI()
        {
            scrollPosition = GUILayout.BeginScrollView(scrollPosition, false, true);
            fieldList.DoLayoutList();
            GUILayout.EndScrollView();
        }

        private float OnElementHeightCallback(int index)
        {
            return 40f;
        }

        private void OnDrawElementCallback(Rect rect, int index, bool isActive, bool isFocused)
        {
            if (index >= data.inheritTypes.Count) //移除元素时报错
                return;
            var field = data.inheritTypes[index];
            EditorGUILayout.BeginHorizontal();
            EditorGUI.BeginChangeCheck();
            rect.height = 20f;
            field.inheritType = EditorGUI.TextField(rect, "类型名称", field.inheritType, GUI.skin.label);
            rect.y += 20f;
            field.genericType = EditorGUI.Toggle(rect, "泛型类型", field.genericType);
            if (EditorGUI.EndChangeCheck())
                SaveData();
            EditorGUILayout.EndHorizontal();
        }
    }
}
#endif